<?php

namespace Home\Controller;


class DocCatController extends BaseController
{
    public function fetchall()
    {
        $list = D('CmsDocCat')->where(array('uid' => MEMBER_LOGINED_UID))->select();
        if (empty($list)) {
            $list = array();
        }
        $listFilterd = array();
        foreach ($list as &$r) {
            $listFilterd[] = array(
                'id' => $r['id'],
                'doc_cnt' => $r['doc_cnt'],
                'title' => $r['title']
            );
        }
        $this->ajaxReturn(array('status' => 1, 'list' => $listFilterd));
    }

    public function add()
    {
        $title = I('post.title', '', 'trim');
        if (empty($title)) {
            $this->error('请输入分类名称');
        }
        $m = D('CmsDocCat');
        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'title' => $title))->find();
        if (!empty($one)) {
            $this->error('已经存在相同名称的分类');
        }
        $data = array();
        $data['uid'] = MEMBER_LOGINED_UID;
        $data['title'] = $title;
        $data['doc_cnt'] = 0;
        $m->add($data);
        $this->success('ok');
    }

    public function edit()
    {
        $title = I('post.title', '', 'trim');
        $id = I('post.id', 0, 'intval');
        if (empty($title)) {
            $this->error('请输入分类名称');
        }
        if (empty($id)) {
            $this->error('ID为空');
        }
        $m = D('CmsDocCat');
        $all = $m->where(array('uid' => MEMBER_LOGINED_UID, 'title' => $title))->select();
        if (empty($all)) {
            $all = array();
        }
        foreach ($all as $r) {
            if ($r['id'] != $id) {
                $this->error('已经存在相同名称的分类');
            }
        }

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('记录不存在');
        }
        $one['title'] = $title;
        $m->save($one);
        $this->success('ok');

    }

    public function delete()
    {
        $id = I('post.id', 0, 'intval');

        $m = D('CmsDocCat');
        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('分类不存在');
        }
        if ($one['doc_cnt'] > 0) {
            $this->error('该分类下存在文档，不能删除');
        }
        $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->delete();
        $this->success('ok');
    }

}